#include "zen_macro.h"

#if !ZEN_IS_GUI || ZEN_OS_WIN

#include "zen_utils.h"
#include "zen_file.h"
#if ZEN_OS_WIN
#include <io.h>
#else
#include <sys/ioctl.h>
#include <unistd.h>
#endif

#include "zen_url.h"

namespace Zen
{

	class Utils__ : public Utils
	{
	public:
		std::string GetAppID() override
		{
			return "";
		}
		std::string GetDeviceID() override
		{
			return "";
		}

		bool IsResourceExist(std::string const& path) override
		{
			return ::_access(path.data(), 0) == 0;
		}

		bool IsDocumentExist(std::string const& path) override
		{
			auto doc = GetDocumentPath(path);
			return ::_access(doc.data(), 0) == 0;
		}

		std::vector<uint8_t> LoadResource(std::string const& path) override
		{
			return File::LoadFileToBuffer(path);
		}

		std::vector<uint8_t> LoadDocument(std::string const& path) override
		{
			return File::LoadFileToBuffer(GetDocumentPath(path));
		}

		bool SaveDocument(std::string const& path, void const* value, size_t size) override
		{
			return File::WriteBufferToFile(GetDocumentPath(path), value, size);
		}

		std::vector<uint8_t> LoadURL(std::string const& url) override
		{
			std::string path = GetDocumentPath("curl.temp~");
			std::string cmd = "curl " + URLUtil::Encode(url) + " -o " + path + " 1>&- 2>&-";
			system(cmd.data());
			return LoadResource(path);
		}

		std::string GetSystemLanguage() override
		{
			return "";
		}

		std::string GetDocumentPath(const std::string& path) override
		{
			return path;
		}

	public:
		static Utils__* Only()
		{
			static auto me = new Utils__;
			return me;
		}
	};

	Utils* Utils::Only()
	{
		return Utils__::Only();
	}
} // namespace Zen

#endif
